import java.net.*;
import java.io.*;

public class UDPEchoServer
{
   DatagramSocket sock;
 
   public static void main(String [] args) throws IOException
   {
      if (args.length != 1)
        throw new RuntimeException("Syntax: java UDPEchoServer <port>");
      int port = Integer.parseInt(args[0]);
      UDPEchoServer echo = new UDPEchoServer(port);
      echo.execute();
   }

   public UDPEchoServer(int port) throws IOException
   {
      sock = new DatagramSocket(port);
      System.out.println("UDP Echo Server running on " + 
                         InetAddress.getLocalHost().getHostName() + 
                         " at port " + port);
      System.out.println("Use ctrl-c to stop server. "); 
   }

   public void execute() throws IOException
   {
      while (true)
      {
         DatagramPacket packet = receive();
         
         String msg = new String(packet.getData(), 0, packet.getLength());
         System.out.println("Empfangene Nachricht: " + msg);
         System.out.println("Addresse: " + packet.getAddress().toString() + " Port: " + packet.getPort());
         sendEcho(packet.getAddress(), 12345, packet.getData(), packet.getLength());
        
      }
   }

   protected DatagramPacket receive() throws IOException
   {
      byte [] buffer = new byte[65535];
      DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
      sock.receive(packet);
      return packet;
   }

   protected void sendEcho(InetAddress addr, int port, byte [] data, int leng)
                                  throws IOException
   {
      DatagramPacket packet = new DatagramPacket(data, leng, addr, port);
      sock.send(packet);
      System.out.println("Sent response.");
   }
}
